//
//  DetailViewController.m
//  AOEProject
//
//  Created by techplus on 9/20/12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//
#define TAG_CATALOGUE 0
#define TAG_CATALOGUE_ELEMENT 1
#define TAG_MATCH 2
#define TAG_GAME 3

#define DATASOURCE_AOE 0;
#define DATASOURCE_HOTNEW 1;

#define MY_BANNER_UNIT_ID @"a15058281c7e81b"

#import "DetailViewController.h"
#import "YouTubeViewController.h"
#import "Match.h"
#import "Catalogue.h"
#import "CatalogueElement.h"
#import "Game.h"
#import "MyCell.h"
#import "AsyncImageView.h"

@implementation DetailViewController
@synthesize list;
@synthesize uiTableView;
@synthesize uiImage;
@synthesize uiAdView;
@synthesize type;
@synthesize TAG_CATALOG_INDEX;
@synthesize TAG_CATALOG_ELEMENT_INDEX;
@synthesize TAG_MATCH_INDEX;
@synthesize lable1;
@synthesize lable2;
@synthesize lable3;
@synthesize controller;
@synthesize backgroundImageView;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

-(id)initWithNibNameAndType:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil :(NSInteger *)Type :(NSInteger *)cIndex :(NSInteger *)ceIndex :(NSInteger *)mIndex{
    
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if(self){
        self.type = Type;
        self.TAG_CATALOG_INDEX = cIndex;
        self.TAG_CATALOG_ELEMENT_INDEX = ceIndex;
        self.TAG_MATCH_INDEX = mIndex;
    }
    return self;
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    //Banner
    bannerView_ = [[GADBannerView alloc]initWithAdSize:kGADAdSizeBanner];
    bannerView_.adUnitID = MY_BANNER_UNIT_ID;
    bannerView_.rootViewController = self;
    [self.uiAdView addSubview:bannerView_];
    [bannerView_ loadRequest:[GADRequest request]];
    
    //
    [self.uiTableView setBackgroundColor:[UIColor clearColor]];
    // Do any additional setup after loading the view from its nib.
    list = [[NSMutableArray alloc]init]; 
    NSLog(@"ViewDidLoaded");
    //int *mType = type;
    switch ((int)type) {
        case TAG_CATALOGUE:
        {
            NSLog(@"Jump to TAG_CATALOG");
            Catalogue *e = [[[Catalogue alloc]initWithCatalogIndex:TAG_CATALOG_INDEX]autorelease];
            [e getCatalogueElements];
            for(CatalogueElement *ce in e.catalogueElements){
                [list addObject:ce];
                [ce release];
            }
            //[e release];
            break;
        }   
        case TAG_CATALOGUE_ELEMENT:
        {
            NSLog(@"Jump to TAG_CATALOG_ELEMENT");
            CatalogueElement *ce =[[CatalogueElement alloc]initWithCatalogIndexAndCEIndex:TAG_CATALOG_INDEX :TAG_CATALOG_ELEMENT_INDEX];
            [ce getMatchs];
            for(Match *m in ce.matchs){
                [list addObject: m];
                [m release];
            }
            break;
        }
        case TAG_MATCH:
        {
            NSLog(@"Jump to TAG_MATCH");
            Match *m = [[[Match alloc]initWithCatalogIndex:TAG_CATALOG_INDEX ceIndex:TAG_CATALOG_ELEMENT_INDEX matchIndex:TAG_MATCH_INDEX]autorelease];
            [m getGames];
            for(Game *g in m.games){
                //[g getAddtionLable:m :m.atrDate];
                [list addObject:g];
                [g release];
            }
            
            break;
        }
        case TAG_GAME:
        {
            
        }
        default:
            break;
    }
    
}

-(void)viewWillAppear:(BOOL)animated {
    AppDelegate *delegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    NSLog(@"TABBAR Background %0.2f, %0.2f", CGRectGetMinX(delegate.tabBarController.tabbarBackground.frame) , CGRectGetMinY(delegate.tabBarController.tabbarBackground.frame));
    self.controller = nil;
    [super viewWillAppear:YES];
    if ([UIDevice currentDevice].orientation!=UIDeviceOrientationLandscapeLeft &&
        [UIDevice currentDevice].orientation!=UIDeviceOrientationLandscapeRight)
    {
        self.backgroundImageView.frame = CGRectMake(0, 0, 320, 480);
        [self.backgroundImageView setImage:[UIImage imageNamed:@"landscape.png"]];
        self.uiTableView.frame = CGRectMake(0, 0, 320, 317);
        //        [self.uiTableView reloadData];
        
//        AppDelegate *delegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
//        delegate.tabBarController.btn1.frame = CGRectMake(0, 430, 80, 50);
//        delegate.tabBarController.btn2.frame = CGRectMake(120, 430, 80, 50);
//        delegate.tabBarController.btn3.frame = CGRectMake(240, 430, 80, 50);
//        delegate.tabBarController.tabbarBackground.frame = CGRectMake(0, 230, 320, 50);
//        delegate.tabBarController.tabbarBackground.image = [UIImage imageNamed:@"tabbar@portrait.png"];
        [delegate.tabBarController doPortrait];
    }
    else
    {
        self.backgroundImageView.frame = CGRectMake(0, 0, 480, 320);
        [self.backgroundImageView setImage:[UIImage imageNamed:@"Default.png"]];
        self.uiTableView.frame = CGRectMake(0, 0, 480, 220);
        //        [self.uiTableView reloadData];
//        AppDelegate *delegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
//        delegate.tabBarController.btn1.frame = CGRectMake(0, 270, 80, 50);
//        delegate.tabBarController.btn2.frame = CGRectMake(200, 270, 80, 50);
//        delegate.tabBarController.btn3.frame = CGRectMake(400, 270, 80, 50);
//        delegate.tabBarController.tabbarBackground.frame = CGRectMake(0, 270, 480, 49);
//        delegate.tabBarController.tabbarBackground.image = [UIImage imageNamed:@"tabbar@landscape.png"];
        [delegate.tabBarController doLandscape];
    }
//    [delegate.tabBarController ShowNewTabBar];
}

- (void)viewDidUnload
{
   
    [self setUiImage:nil];
    [self setUiAdView:nil];
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
    
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    //    return (interfaceOrientation == UIInterfaceOrientationPortrait);
    return YES;
}

- (void)willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration
{
    AppDelegate *delegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    if (toInterfaceOrientation == UIInterfaceOrientationLandscapeLeft ||
        toInterfaceOrientation == UIInterfaceOrientationLandscapeRight)
    {
        self.backgroundImageView.frame = CGRectMake(0, 0, 480, 320);
        [self.backgroundImageView setImage:[UIImage imageNamed:@"Default.png"]];
        self.uiTableView.frame = CGRectMake(0, 0, 480, 220);
        [self.uiTableView reloadData];
        
        
//        delegate.tabBarController.btn1.frame = CGRectMake(0, 270, 80, 50);
//        delegate.tabBarController.btn2.frame = CGRectMake(200, 270, 80, 50);
//        delegate.tabBarController.btn3.frame = CGRectMake(400, 270, 80, 50);
//        delegate.tabBarController.tabbarBackground.frame = CGRectMake(0, 270, 480, 49);
//        delegate.tabBarController.tabbarBackground.image = [UIImage imageNamed:@"tabbar@landscape.png"];
        [delegate.tabBarController doLandscape];
    }
    else
    {
        self.backgroundImageView.frame = CGRectMake(0, 0, 320, 480);
        [self.backgroundImageView setImage:[UIImage imageNamed:@"landscape.png"]];
        self.uiTableView.frame = CGRectMake(0, 0, 320, 317);
        [self.uiTableView reloadData];
        
        AppDelegate *delegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
//        delegate.tabBarController.btn1.frame = CGRectMake(0, 430, 80, 50);
//        delegate.tabBarController.btn2.frame = CGRectMake(120, 430, 80, 50);
//        delegate.tabBarController.btn3.frame = CGRectMake(240, 430, 80, 50);
//        delegate.tabBarController.tabbarBackground.frame = CGRectMake(0, 430, 320, 50);
//        delegate.tabBarController.tabbarBackground.image = [UIImage imageNamed:@"tabbar@portrait.png"];
        [delegate.tabBarController doPortrait];

    }
}

#pragma mark - Table view method

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return list.count;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 100;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier;
    static NSString *NibNamed;
    
    if ([UIDevice currentDevice].orientation!=UIDeviceOrientationLandscapeLeft &&
        [UIDevice currentDevice].orientation!=UIDeviceOrientationLandscapeRight)
    {
        CellIdentifier= @"MyCellPortrait";
        NibNamed = @"MyCellPortrait";
    }
    else
    {
        CellIdentifier= @"MyCellLandscape";
        NibNamed = @"MyCellLandscape";
    }
    
    MyCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    
    if(cell ==nil)
    {
        cell = [[[NSBundle mainBundle] loadNibNamed:NibNamed owner:self options:nil] objectAtIndex:0];
        //cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    }

    else{
        AsyncImageView* oldImage = (AsyncImageView*)
        [cell.contentView viewWithTag:999];
        [oldImage removeFromSuperview];
        
    }
    
    //NSLog([NSString stringWithFormat:@"%d",indexPath.row]);
    //Match *e = (Match *)[list objectAtIndex:indexPath.row];
    switch ((int)type) {
        case TAG_CATALOGUE:
        {
            CatalogueElement *ce = (CatalogueElement *)[list objectAtIndex:indexPath.row];
            cell.myCellTitle.text = ce.atrName;
            break;
        }
        case TAG_CATALOGUE_ELEMENT:
        {
            NSLog(@"Jump to TAG_CATALOG_ELEMENT 2");
            
            Match *m = (Match *)[list objectAtIndex:indexPath.row];
            cell.myCellTitle.text = m.atrTitle;
            cell.myCellDate.text = m.atrDate;
            cell.myCellType.text = m.atrType;
            break;
        }
        case TAG_MATCH:
        {
            Game *g = (Game *)[list objectAtIndex:indexPath.row];
            
            cell.myCellTitle.text = lable1;
            cell.myCellDate.text = g.atrName;
            cell.myCellType.text = lable2;
            
            NSString *imageURL = [[NSString alloc]initWithFormat:@"http://img.youtube.com/vi/%@/1.jpg",g.gUrl];
            
            CGRect frame;
            frame.size.width=150; frame.size.height=90;
            frame.origin.x=0; frame.origin.y=0;
            
            AsyncImageView* asyncImage = [[[AsyncImageView alloc]
                                           initWithFrame:frame] autorelease];
            asyncImage.tag = 999;
            
            NSURL* url = [[[NSURL alloc]initWithString:imageURL]autorelease];
            [asyncImage loadImageFromURL:url];
            
            //[cell.contentView addSubview:asyncImage];
            [cell.myCellUIImage addSubview:asyncImage];
            cell.myCellUIImage.image = nil;
            //[cell loadImage:imageURL];
            [imageURL release];
            break;
        }
        case TAG_GAME:
        {            
            break;
        }
        default:
            break;
    }
    
    //[cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
    
    //e release];
    return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    switch ((int)type) {
        case TAG_CATALOGUE:
        {
            CatalogueElement *ce = (CatalogueElement *)[list objectAtIndex:indexPath.row];
            
            DetailViewController *dvc = [[DetailViewController alloc]initWithNibNameAndType:@"DetailViewController" bundle:nil:(NSInteger *)1 :ce.TAG_CATALOG_INDEX :ce.TAG_CATALOG_ELEMENT_INDEX:nil];
          
            [self.navigationController pushViewController:dvc animated:YES];
            
            //[ce release];
            [dvc release];
            break;
        }
        case TAG_CATALOGUE_ELEMENT:
        {
            Match *m = (Match *)[list objectAtIndex:indexPath.row];
            
            DetailViewController *dvc = [[DetailViewController alloc]initWithNibNameAndType:@"DetailViewController" bundle:nil :(NSInteger *)2 :m.TAG_CATALOG_INDEX:m.TAG_CATALOG_ELEMENT_INDEX:m.TAG_MATCH_INDEX];
            
            dvc.lable1 = m.atrTitle;
            dvc.lable2 = m.atrDate;
            dvc.lable3 = m.atrType;
            
            [self.navigationController pushViewController:dvc animated:YES];
            [dvc release];
            //[m release];
            break;
        }
        case TAG_MATCH:
        {
            Game *g = (Game *)[list objectAtIndex:indexPath.row];
            NSString *url = [NSString stringWithFormat:@"http://www.youtube.com/watch?v=%@", g.gUrl];
//            NSLog(@"Link: %@", g.gUrl);
//            YouTubeViewController *yvc = [[YouTubeViewController alloc]initWithNibName:@"YouTubeViewController" bundle:nil];
//            
//            [yvc loadYoutubeLink:g.gUrl];
//            yvc.hidesBottomBarWhenPushed = YES;
//            yvc.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
////            //[self.navigationController setNavigationBarHidden:YES];
////            //[self.navigationController pushViewController:yvc animated:YES];
//            [self presentModalViewController:yvc animated:YES];
//            
//            [yvc release];
            
            
            //----------------Play Youtube Movie by MPMoviePlayerController-----------------------
            self.controller = [[LBYouTubePlayerViewController alloc] initWithYouTubeURL:[NSURL URLWithString:url] quality:LBYouTubeVideoQualityLarge];
            self.controller.delegate = self;
            self.controller.view.frame = CGRectZero;
            self.controller.view.center = self.view.center;
            [self.view addSubview:self.controller.view];
//            [[[UIApplication sharedApplication] keyWindow] addSubview:bannerView_];
//            [[[UIApplication sharedApplication] keyWindow] bringSubviewToFront:bannerView_];
            break;
        }
        case TAG_GAME:
        {
            
            break;
        }
        default:
            break;
    }

}

- (void)dealloc {
    [lable1 release];
    [lable2 release];
    [lable3 release];
    [list release];
    [uiTableView release];
    [uiImage release];
    [uiAdView release];
    [bannerView_ release];
    self.controller.delegate = nil;
    [super dealloc];
}

-(void)youTubePlayerViewController:(LBYouTubePlayerViewController *)controller didSuccessfullyExtractYouTubeURL:(NSURL *)videoURL {
    NSLog(@"Did extract video source:%@", videoURL);
    AppDelegate *delegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    [delegate.tabBarController hideNewTabBar];
}

-(void)youTubePlayerViewController:(LBYouTubePlayerViewController *)controller failedExtractingYouTubeURLWithError:(NSError *)error {
    NSLog(@"Failed loading video due to error:%@", error);
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Lỗi" message:@"Không thể xem được video. Xin vui lòng thử lại sau!" delegate:self cancelButtonTitle:@"Đồng ý" otherButtonTitles:nil, nil];
    [alert show];
}
@end
